<template>
	<view class="image-list-wrapper">
		<view class="image-list-item" v-for="(item, index) in imageList" :key="index">
			<image mode="aspectFill" @click="previewImage(index)" :src="item"></image>
			<view class="clear" @click="removeImg(index)">x</view>
		</view>
		<view class="upload-wrapper" v-if="imageList.length < max" @click="onuploadClick">
			<!-- <view class="add">
				+
			</view> -->
			<view class="add">
				<image src="/static/icon/8.png" mode=""></image>
			</view>
		</view>

		<view v-for="(path,index) in tempFilePaths" :key="index">
			<canvas :style="{width: drawWidth+'px', height: drawHeight+'px',position:'absolute',left:'-10000px'}" :canvasId="'canvas'+index"></canvas>
			<image style="visibility: hidden;position: absolute;" :id="'rawImage'+index" @load="onImageLoad" :src="path"
				mode="aspectFit"></image>
		</view>
		<!-- <image ref='compressedImage' :src="src1" mode="aspectFit"></image> -->
	</view>
</template>

<script>
	export default {
		name: "MyUploader",
		components: {},
		props: {
			value: {
				type: Array,
				default: () => []
			},
			//最多上传几个文件
			max: {
				type: Number,
				default: 9,
			},
			//大于100K 需要压缩
			compressSize: {
				type: Number,
				default: 204800
			},
			needCompress: {
				type: Boolean,
				default: true
			},
			//默认压缩后宽度400px
			drawWidth: {
				type: Number,
				default: 400
			},
			//默认压缩后宽度400px
			drawHeight: {
				type: Number,
				default: 400
			}
		},
		data() {
			return {
				src: '',
				src1: '',
				//原始图片宽高
				rawWidth: null,
				rawHeight: null,
				imageList: [],
				img: {},
				fileIds: [],
				isFromFather: true,
				tempFilePaths: [],
				tempFiles: []			
			};
		},
		watch: {
			value(newVal) {
				// console.log('从父组件传入的值',newVal)		
				if (this.isFromFather) {
					this.downLoadFiles(newVal)
				} else {
					this.isFromFather = true
				}

			}
		},
		onReady() {

		},
		methods: {
			onuploadClick() {
				let that = this;
				let count = this.max - this.imageList.length;

				uni.chooseImage({
					count: count > 9 ? 9 : count, //默认9
					sizeType: ["compressed"], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ["album", "camera"], //从相册选择
					success: (res) => {
						console.log(res)
						console.log(JSON.stringify(res.tempFilePaths));
						this.tempFilePaths = res.tempFilePaths;
						// this.img = res.tempFiles[0]
						this.tempFiles = res.tempFiles
						uni.showLoading({
							title: "图片上传中",
							mask: true
						})
					},
				});
			},
			//图片加载后，压缩
			async onImageLoad(e) {

				console.log('onImageLoad', e.target)

				let that = this
				let rawWidth = e.target.width;
				let rawHeight = e.target.height;

				let drawWidth = this.drawWidth
				let drawHeight = this.drawHeight
				if (rawWidth > rawHeight) {
					drawHeight = drawWidth * rawHeight / rawWidth;
				} else {
					drawWidth = drawHeight * rawWidth / rawHeight
				}

				console.log(rawWidth, rawHeight, drawWidth, drawHeight)
				//需要压缩，并且图片大小超过compressSize
				// && this.img.size > this.compressSize
				//图片地址
				let index = e.target.id.replace("rawImage", '')
		
				let filePath = this.tempFilePaths[index]

				if (this.needCompress) {
					// console.log('this.img', this.img)
					try {
						//获取压缩后的图
						filePath = await this.compressImage(filePath, drawWidth, drawHeight, index)

					} catch (e) {
						//TODO handle the exception
						console.log('compressImage error', e)
					}

				}
				this.imageList.push(filePath)
				let base64 = await this.urlTobase64(filePath);
				// console.log(base64)
				let fileId = await this.uploadFile(base64)
				this.fileIds.push(fileId)
				this.isFromFather = false
				// console.log(this.fileIds)
				if (this.fileIds.length === this.imageList.length) {
					uni.hideLoading()
					this.$emit('input', this.fileIds)
				}

			},
			//根据比例算出来的图片高度
			compressImage(filePath, drawWidth, drawHeight, index) {
				return new Promise((resolve, reject) => {
					let that = this
					let canvasId = 'canvas' + index
					//小程序方法一定要加参数 this
					const ctx = uni.createCanvasContext(canvasId, this)
					//宽度为屏幕宽度，算出图片等比例的高度，

					console.log(drawWidth, drawHeight)
					ctx.drawImage(filePath, 0, 0, drawWidth, drawHeight);
					ctx.draw(false, setTimeout(() => {
						uni.canvasToTempFilePath({
							canvasId: canvasId,
							x: 0,
							y: 0,
							width: drawWidth,
							height: drawHeight,
							quality: 0.8, //最高质量，只通过尺寸放缩去压缩，画的时候都按最高质量来画
							success: (res) => {
								console.log(res.tempFilePath)
								resolve(res.tempFilePath)
							},
							fail: err => {
								reject(err)
							}
						}, that)
					}, 200));
				})

			},
			previewImage(index) {
				uni.previewImage({
					urls: this.imageList,
					current: index,
					longPressActions: {
						itemList: ["发送给朋友", "保存图片", "收藏"],
						success: function(data) {
							console.log("选中了第" + (data.tapIndex + 1) + "个按钮,第" + (data.index + 1) + "张图片");
						},
						fail: function(err) {
							console.log(err.errMsg);
						},
					},
				});
			},
			urlTobase64(url) {
				return new Promise((resolve, reject) => {
					uni.getFileSystemManager().readFile({
						filePath: url, //选择图片返回的相对路径
						encoding: 'base64', //编码格式
						success: res => { //成功的回调
							let base64 = 'data:image/jpeg;base64,' + res.data //不加上这串字符，在页面无法显示的哦
							// this.dataList.picList.push(base64);
							// console.log(base64)
							let file = {
								fileData: base64,
								fileName: url
							};
							resolve(file)
							// this.uploadFile(file)
						},
						fail: err => {
							reject(err)
						}
					})
				})
			},
			// 上传文件
			uploadFile(file) {
				return new Promise((resolve, reject) => {
					// console.log(file)
					this.$http.post('common/file/upload', file).then(res => {
						if (res.code === 10000) {
							// this.baseArr.push(res.data.id)
							resolve(res.data.id)

						}
					})
				})

			},
			removeImg(index) {
				this.imageList.splice(index, 1);
				let fileId = this.fileIds[index]
				this.fileIds.splice(index, 1);
				this.isFromFather = false
				this.$emit('input', this.fileIds)
				//删除服务器上的文件
				this.$http.post('common/file/delete', {
					id: fileId
				}).then(res => {

				})
			},
			setImages(fileIds) {
				console.log('传入', fileIds)
				this.downLoadFiles(fileIds)
			},
			downLoadFiles(fileIds) {
				let that = this
				fileIds.forEach(id => {
					console.log(id)
					this.$http.post('common/file/download', {
						id: id
					}).then(res => {
						console.log(res)
						if (res.code == 10000) {
							that.fileIds.push(id);
							that.imageList.push(res.data.fileData)
						}
					})
				})
			}
		},
	};
</script>
<style lang="less" scoped>
	.upload-wrapper {
		margin: 12rpx;
		width: 220rpx;
		height: 220rpx;
		// border: 1rpx solid #ccc;
		display: flex;
		justify-content: center;
		align-items: center;

		// .add {
		// 	font-size: 100rpx;
		// 	color: #ccc;
		// }
		.add {
			width: 220rpx;
			height: 220rpx;

			image {
				width: 100%;
				height: 100%;
			}
		}
	}

	.image-list-wrapper {
		display: flex;
		flex-wrap: wrap;
		// 
		padding-left: 4rpx;

		.image-list-item {
			margin: 12rpx;
			width: 220rpx;
			height: 220rpx;
			position: relative;

			image {
				// padding: 2rpx;
				border: 1rpx solid #ccc;
				max-width: 100%;
				max-height: 100%;
			}

			.clear {
				position: absolute;
				right: 0rpx;
				top: 0rpx;
				// color: grey;
				color: #fff;
				border: 1rpx solid grey;
				background: #000000;
				opacity: 0.34;
				height: 40rpx;
				font-size: 30rpx;
				width: 40rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				padding-bottom: 6rpx;
			}
		}
	}
</style>